﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;

namespace SignalrService.SignalrService
{
    public class CommonHub: BaseHub
    {

        private readonly IOnlineClientManager _onlineClientManager;
        private readonly IHttpContextAccessor _httpContextAccessor;

        public CommonHub(IOnlineClientManager onlineClientManager, IHttpContextAccessor httpContextAccessor)
        {
            _onlineClientManager = onlineClientManager;
            _httpContextAccessor = httpContextAccessor;
            _onlineClientManager.ClientConnected += _onlineClientManager_ClientConnected;
            _onlineClientManager.ClientDisconnected += _onlineClientManager_ClientDisconnected;
        }

        private void _onlineClientManager_ClientDisconnected(object sender, OnlineClientEventArgs e)
        {
           
        }

        private void _onlineClientManager_ClientConnected(object sender, OnlineClientEventArgs e)
        {
           
        }

        public async Task SendMessage(string user, string message)
        {
            await Clients.All.SendAsync("ReceiveMessage", user, message);
        }

        public override async Task OnConnectedAsync()
        {
            await base.OnConnectedAsync();
            var client= _onlineClientManager.GetByConnectionId(Context.ConnectionId);
            if (client == null)
            {
                client = new OnlineClient(
                    Context.ConnectionId,
                    GetIpAddressOfClient(Context),
                    100);
                _onlineClientManager.Add(client);
            }
            _onlineClientManager.Add(client);
            Console.WriteLine(client.ConnectionId + "---:" + client.IpAddress + "链接成功");
            await SendMessage(client.ConnectionId, client.ConnectionId+"---:"+client.IpAddress+"链接成功");
        }

        public override async Task OnDisconnectedAsync(Exception exception)
        {
            await base.OnDisconnectedAsync(exception);
            try
            {
                _onlineClientManager.Remove(Context.ConnectionId);
            }
            catch (Exception ex)
            {

            }
        }


        private string GetIpAddressOfClient(HubCallerContext context)
        {
            try
            {
                var httpContext = _httpContextAccessor.HttpContext;
                return httpContext?.Connection?.RemoteIpAddress?.ToString();
            }
            catch (Exception ex)
            {
            }
            return null;
        }

    }
}
